package com.kingsoft.dc.khaos.module.spark.util

import org.apache.commons.lang3.StringUtils
import org.apache.commons.logging.LogFactory

object FieldNameUtils {
  protected val log = LogFactory.getLog(this.getClass())

  var fieldNameMapping:Map[String,String] = Map()

  def getSubMap(map: scala.collection.mutable.Map[String, String],prefix:String):Map[String,String] = {
    var subMap:Map[String,String] = Map()
    val keys = map.keySet
    keys.foreach(key => {
      if (key.startsWith(prefix)) {
        subMap += (StringUtils.substringAfter(key,prefix)-> map.getOrElse(key,key))
      }
    })
    subMap
  }

  def getFieldNameMapping(userConf: scala.collection.mutable.Map[String, String]): Map[String,String] = {
    fieldNameMapping = getSubMap(userConf,"rename.")
    if (!fieldNameMapping.isEmpty) {
      log.info("fieldNameMapping:" + fieldNameMapping)
    }
    fieldNameMapping
  }

  def formatFieldName(oldField:String):String = {
      if (fieldNameMapping.contains(oldField)) {
        fieldNameMapping.get(oldField)
      }
      oldField
  }

  def indexOfIgnoreCase(structFieldNames:Array[String],field:String):Int = {
    for (i <- 0 until structFieldNames.length if structFieldNames(i).equalsIgnoreCase(field)) {
      return i
    }
    return -1
  }
}